package com.ecnu.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ecnu.common.constant.HttpStatus;
import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.common.core.domain.model.LoginUser;
import com.ecnu.common.core.page.PageDomain;
import com.ecnu.common.core.page.TableDataInfo;
import com.ecnu.common.utils.OtherUtil;
import com.ecnu.common.utils.PageUtils;
import com.ecnu.common.utils.StringUtils;
import com.ecnu.common.utils.http.HttpUtils;
import com.ecnu.common.utils.http.UrlUtils;
import com.ecnu.common.utils.ip.IpUtils;
import com.ecnu.system.domain.IncubationFile;
import com.ecnu.system.domain.dto.ProjectIndexFileDTO;
import com.ecnu.system.domain.dto.incubation.FilePageDTO;
import com.ecnu.system.domain.dto.incubation.IncubationFileDTO;
import com.ecnu.system.domain.vo.Incubation.IncubationFileVO;
import com.ecnu.system.mapper.IncubationFileMapper;
import com.ecnu.system.service.IIncubationFactoryService;
import com.ecnu.system.service.IIncubationFileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

import static com.ecnu.system.domain.menu.OtherMenu.*;

/**
 * <p>
 * ecnu_二期_成果资料表 服务实现类
 * </p>
 *
 * @author zdn
 * @since 2025-10-16
 */
@Service
public class IncubationFileServiceImpl extends ServiceImpl<IncubationFileMapper, IncubationFile> implements IIncubationFileService {

    @Autowired
    private IIncubationFactoryService incubationFactoryService;
    @Autowired
    private IncubationFileMapper incubationFileMapper;
    @Value("${ai.pdf.parse-status-url}")
    private String parseStatusUrl;

    protected void startPage(PageDomain pageDomain) {
        PageUtils.startPage(pageDomain);
    }

    @Override
    public TableDataInfo List(FilePageDTO dto) {

        IncubationFile incubationFile = new IncubationFile();
        incubationFile.setIncuId(dto.getIncuId());
        startPage(dto.getPageDomain());
        List<IncubationFileVO> incubationFiles = incubationFileMapper.listForUser(incubationFile);
        incubationFiles.forEach(projectStageMissionVO -> {
            switch (projectStageMissionVO.getFileType()){
                case 文献:
                    projectStageMissionVO.setFileTypeName("文献");
                    break;
                case 数据:
                    projectStageMissionVO.setFileTypeName("数据");
                    break;
                case 代码:
                    projectStageMissionVO.setFileTypeName("代码");
                    break;
                case 其他:
                    projectStageMissionVO.setFileTypeName("其他");
                    break;
            }
            String indexFileDTO = fileToVo(projectStageMissionVO);
            projectStageMissionVO.setFullurl(indexFileDTO);
        });
        return OtherUtil.tableSuccess(incubationFiles);
    }
    private String fileToVo(IncubationFileVO projectFiles) {
        String fullurl = null;
        if (StringUtils.isNotBlank(projectFiles.getUrl())) {
            String url = projectFiles.getUrl().startsWith("/")?
                    projectFiles.getUrl():"/"+projectFiles.getUrl();
            fullurl=UrlUtils.getUrl()  + url;

        }
        return fullurl;
    }
    @Override
    public AjaxResult edit(List<IncubationFileDTO> dto, LoginUser loginUser) {
       try {
           dto.forEach(d -> {
               Boolean fileStatus = incubationFactoryService.fileToSave(d, loginUser);
           });
           return AjaxResult.success("保存成功");
       }catch (Exception e){
           log.error("文件添加错误："+e.getMessage());
           return AjaxResult.error("保存失败，请联系管理员");
       }
    }

    @Override
    public Map<String, Object> getFileList(List<String> collect) {
        LambdaQueryWrapper<IncubationFile> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(IncubationFile::getIncuId, collect)
                .eq(IncubationFile::getDelFlag, "0")
                .eq(IncubationFile::getFileType, "1")
                .isNotNull(IncubationFile::getUrl)
                .ne(IncubationFile::getUrl,"");
        List<IncubationFile> incubationFiles = list(wrapper);
        LinkedHashMap<String, Object> hashMap = new LinkedHashMap<>();
        incubationFiles.forEach(incubationFile -> {
            String[] split = incubationFile.getUrl().split("/");
            System.out.println(incubationFile.getUrl());
//            String url = parseStatusUrl+"/api/ApiPdf/import-and-parse";
            String url = parseStatusUrl+"/api/ApiPdf/evaluate-feasibility";
            //包装参数
            HashMap<String, Object> map = new HashMap<>();
            map.put("FileName", split[6]);//文件名称
            map.put("Year", split[3]);//年份包
            map.put("Month", split[4]);//月份包
            map.put("Day", split[5]);//日份包
            map.put("ModelName","cnki");
            String jsonString = JSON.toJSONString(map);

            String contentType = "application/json";
            //访问返回
            String token = HttpUtils.sendPost(url, jsonString, contentType,new HashMap<>());
            //调整状态
            HashMap<String, Object> maps = (HashMap<String, Object>) JSON.parseObject(token, HashMap.class);
            if (maps.get("IsSuccess").toString().equals("true")) {
                //调整为原始的数据
                System.out.println(maps);
            }else {
                log.error("获取Ai评估结果失败\n"+maps.get("ErrorMessage"));
            }
        });

        return hashMap;
    }

    @Override
    public Map<String, Object> editExtract(List<String> collect) {
        LambdaQueryWrapper<IncubationFile> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(IncubationFile::getIncuId, collect)
                .eq(IncubationFile::getDelFlag, "0")
                .eq(IncubationFile::getFileType, "1");
        List<IncubationFile> incubationFiles = list(wrapper);
        LinkedHashMap<String, Object> hashMap = new LinkedHashMap<>();
        incubationFiles.forEach(incubationFile -> {
            String[] split = incubationFile.getUrl().split("/");
            System.out.println(incubationFile.getUrl());
            String url = parseStatusUrl+"/api/ApiPdf/import-and-parse";
//            String url = parseStatusUrl+"/api/ApiPdf/evaluate-feasibility";
            //包装参数
            HashMap<String, Object> map = new HashMap<>();
            map.put("FileName", split[6]);//文件名称
            map.put("Year", split[3]);//年份包
            map.put("Month", split[4]);//月份包
            map.put("Day", split[5]);//日份包
            map.put("ModelName","cnki");
            map.put("incuId", incubationFile.getIncuId());
            map.put("TemplateId", 3);
            String jsonString = JSON.toJSONString(map);

            String contentType = "application/json";
            //访问返回
            String token = HttpUtils.sendPost(url, jsonString, contentType,new HashMap<>());
            //调整状态
            HashMap<String, Object> maps = (HashMap<String, Object>) JSON.parseObject(token, HashMap.class);
            hashMap.putAll( maps);
        });
        return hashMap;
    }
}
